package cn.wgx.module.ent.web;

import cn.wgx.common.base.IBaseController;
import cn.wgx.common.entity.ent.EntUser;
import cn.wgx.common.entity.ent.Enterprise;
import cn.wgx.common.security.client.config.entity.LoginAppUser;
import cn.wgx.common.security.util.SysUserUtil;
import cn.wgx.common.util.ResponseDataUtil;
import cn.wgx.module.ent.service.EntDeptService;
import cn.wgx.module.ent.service.EntUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Api(tags = "5.1 企业部门管理")
//@RestController
@RequestMapping("/api/entDept")
public class EntDeptCtrl extends IBaseController<EntDeptService, Enterprise> {

    @Autowired
    EntUserService entUserService;

    @ApiOperation(value = "新增部门", notes = "pid不能为0")
    @PostMapping("add")
    public Map add(@RequestBody Enterprise enterprise) {
        if (enterprise.getPid() == 0) {
            return ResponseDataUtil.returnErrorMap("pid不能为0");
        }
        Enterprise byId = service.getById(enterprise.getPid());
        if (!SysUserUtil.getLoginAppUser().getUser_id().equals(byId.getCreateUserId())) {
            return ResponseDataUtil.returnErrorMap("非企业管理员不可以创建");
        }
        return ResponseDataUtil.returnData(service.save(enterprise));
    }

    @ApiOperation(value = "根据entCode删除", notes = "必填：entCode")
    @DeleteMapping("delAll")
    public Map del(@RequestParam String entCode) {
        LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser(null);
        if (!loginAppUser.getUser_id().equals(service.getOneByCode(entCode).getCreateUserId())) {
            return ResponseDataUtil.returnErrorMap("非企业管理员不可以删除");
        }
        QueryWrapper<EntUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("entCode", entCode);
        List<EntUser> list = entUserService.list(queryWrapper);
        if (list.size() > 0) {
            return ResponseDataUtil.returnErrorMap("不可删除，部门下有用户");
        }
        return ResponseDataUtil.returnData(service.del(entCode));
    }

}
